<template>
  <div class="patient-page">
    <cp-nav-bar :title="isSel ? '选择患者' : '家庭档案'"> </cp-nav-bar>
    <div class="patient-change" v-if="isSel">
      <h3>请选择患者信息</h3>
      <p>已便医生给出更准确的治疗,信息仅医生可见</p>
    </div>
    <div class="patient-list">
      <div
        v-for="item in patientList"
        :key="item.id"
        class="patient-item"
        @click="PatientId(item.id)"
        :class="{ selected: selectedPatientId === item.id }"
      >
        <div class="info">
          <span class="name">{{ item.name }}</span>
          <span class="id">{{
            item.idCard.replace(/^(.{6})(?:\d+)(.{4})$/, '\$1********\$2')
          }}</span>
          <span>{{ item.gender == 0 ? '女' : '男' }}</span>
          <span>{{ item.age }}岁</span>
        </div>
        <div @click="showPopup(item)" class="icon"><cp-icon name="user-edit"></cp-icon></div>
        <div class="tag" v-if="item.defaultFlag === 1">默认</div>
      </div>
      <div @click="openDialog" class="patient-add" v-if="patientList.length < 6">
        <cp-icon name="user-add" />
        <p>添加患者</p>
      </div>
      <div class="patient-tip">最多可添加6人</div>
    </div>
    <div class="patient-next" v-if="isSel">
      <van-button type="primary" round block @click="next">下一步</van-button>
    </div>
    <van-popup v-model:show="show" position="bottom">
      <cp-nav-bar
        :title="patient.id ? '编辑患者' : '新增患者'"
        @click-right="submit"
        right-text="保存"
        :back="closeDialog"
      >
      </cp-nav-bar>
      <van-form autocomplete="off">
        <van-field v-model="patient.name" label="真实姓名" placeholder="请输入真实姓名"></van-field>
        <van-field
          v-model="patient.idCard"
          label="身份证号"
          placeholder="请输入身份证号"
        ></van-field>
        <van-field label="性别">
          <template #input>
            <cp-radio-btn v-model="patient.gender" :options="options"></cp-radio-btn>
          </template>
        </van-field>
        <van-field label="默认就诊人">
          <template #input>
            <van-checkbox round v-model="defaultFlag" />
          </template>
        </van-field>
      </van-form>
      <van-action-bar>
        <van-action-bar-button
          @click="remove"
          type="danger"
          text="删除"
          v-if="patient.id ? true : false"
        ></van-action-bar-button>
      </van-action-bar>
    </van-popup>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, computed } from 'vue'
import { getPatientList, addPatient, editPatient, delPatient } from '@/api/user'
import type { PatientList, Patient } from '@/types/user'
import { showFailToast, showSuccessToast, showConfirmDialog } from 'vant'
import 'vant/es/toast/style'
import Validator from 'id-validator'
import { useRoute, useRouter } from 'vue-router'
import { useConsultStore } from '@/stores'

const patientList = ref<PatientList>([])

const loadList = async () => {
  const { data } = await getPatientList()
  patientList.value = data
  if (isSel.value && data.length > 0) {
    const defPatient = data.find((item) => item.defaultFlag === 1)
    if (defPatient) selectedPatientId.value = defPatient.id
    else selectedPatientId.value = data[0].id
  }
}

const show = ref(false)
const openDialog = () => {
  patient.value = { ...defaultPatient }
  show.value = true
}

const closeDialog = () => {
  show.value = false
}

const options = [
  { label: '男', value: 1 },
  { label: '女', value: 0 },
]

//存储选中的性别的value值
const gender = ref(0)

const defaultPatient: Patient = {
  name: '',
  idCard: '',
  gender: 1,
  defaultFlag: 0,
}

const patient = ref<Patient>({ ...defaultPatient })

const defaultFlag = ref(false)

const cardValid = new Validator()

const submit = async () => {
  if (!patient.value.name) return showFailToast('请输入患者名字!')
  if (!patient.value.idCard) return showFailToast('请输入患者身份证!')
  if (!cardValid.isValid(patient.value.idCard)) return showFailToast('身份证格式错误!')
  const { sex } = cardValid.getInfo(patient.value.idCard)
  const idCardGender = sex ? 1 : 0
  if (patient.value.gender !== idCardGender) return showFailToast('选择的性别和身份证不一致!')
  try {
    patient.value.id ? await editPatient(patient.value) : await addPatient(patient.value)
    closeDialog()
    loadList()
    showSuccessToast(patient.value.id ? '编辑成功' : '保存成功')
  } catch (error) {
    console.log(error)
  }
}

const showPopup = (item?: Patient) => {
  if (item) {
    const { id, gender, name, idCard, defaultFlag } = item
    patient.value = { id, gender, name, idCard, defaultFlag }
  } else {
    patient.value = { ...defaultPatient }
  }
  show.value = true
}

const remove = () => {
  if (patient.value.id) {
    showConfirmDialog({
      title: '温馨提示',
      message: `您确认要删除${patient.value.name}患者信息吗?`,
    })
      .then(async () => {
        await delPatient(patient.value.id)
        show.value = false
        loadList()
        showSuccessToast('删除成功')
      })
      .catch(() => {})
  }
}

const route = useRoute()

const isSel = computed(() => route.query.isSel === '1')

const selectedPatientId = ref<string | undefined>('')

const PatientId = (id: string | undefined) => {
  if (isSel.value) {
    selectedPatientId.value = id
  }
}

const store = useConsultStore()
const router = useRouter()

const next = async () => {
  if (!selectedPatientId.value) return showFailToast('请选择问诊患者')
  store.setPatient(selectedPatientId.value)
  router.push('/consult/pay')
}

onMounted(() => {
  loadList()
})

watch(defaultFlag, () => {
  // console.log('是否默认患者', defaultFlag)
  patient.value.defaultFlag = defaultFlag.value ? 1 : 0
})
</script>

<style lang="scss" scoped>
::v-deep .van-popup {
  width: 100%;
  height: 100%;
  padding-top: 45px;
  box-sizing: border-box;
}
.patient-page {
  padding: 46px 0 80px;
}
.patient-change {
  padding: 15px;
  > h3 {
    font-weight: normal;
    margin-bottom: 5px;
  }
  > p {
    color: var(--cp-text3);
  }
}
.patient-next {
  padding: 15px;
  background-color: #fff;
  position: fixed;
  left: 0;
  bottom: 0;
  width: 100%;
  height: 80px;
  box-sizing: border-box;
}
.patient-list {
  padding: 15px;
}
.patient-item {
  display: flex;
  align-items: center;
  padding: 15px;
  background-color: var(--cp-bg);
  border-radius: 8px;
  margin-bottom: 15px;
  position: relative;
  border: 1px solid var(--cp-bg);
  transition: all 0.3s;
  overflow: hidden;
  .info {
    display: flex;
    flex-wrap: wrap;
    flex: 1;
    span {
      color: var(--cp-tip);
      margin-right: 20px;
      line-height: 30px;
      &.name {
        font-size: 16px;
        color: var(--cp-text1);
        width: 80px;
        margin-right: 0;
      }
      &.id {
        color: var(--cp-text2);
        width: 180px;
      }
    }
  }
  .icon {
    color: var(--cp-tag);
    width: 20px;
    text-align: center;
  }
  .tag {
    position: absolute;
    right: 60px;
    top: 21px;
    width: 30px;
    height: 16px;
    font-size: 10px;
    color: #fff;
    background-color: var(--cp-primary);
    border-radius: 2px;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  &.selected {
    border-color: var(--cp-primary);
    background-color: var(--cp-plain);
    .icon {
      color: var(--cp-primary);
    }
  }
}
.patient-add {
  background-color: var(--cp-bg);
  color: var(--cp-primary);
  text-align: center;
  padding: 15px 0;
  border-radius: 8px;
  .cp-icon {
    font-size: 24px;
  }
}
.patient-tip {
  color: var(--cp-tag);
  padding: 12px 0;
}
</style>
